package com.canbot.u05.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.canbot.u05.utils.Logger;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * Created by zmp on 2017/5/16.
 * 录音控件
 */

public class MyRecordView extends View {

        private int measuredHeight;

        private int measuredWidth;

        private int centerHeight;

        private int centerWidth;

        private String time;

        private Paint textPaint;

        private Paint redPaint;

        private int maxCount;

        private int count;

        private ISizeChangeListener listener;

        private String TAG = "MyRecordView";

        private Random random;

        private float maxH;

        private float minH;

        private MediaRecorder mRecorder;

        private String fileName;

        public MyRecordView(Context context) {
                this(context, null);
        }

        public MyRecordView(Context context, @Nullable AttributeSet attrs) {
                this(context, attrs, 0);
        }

        public MyRecordView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
                super(context, attrs, defStyleAttr);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
                super.onSizeChanged(w, h, oldw, oldh);
                measuredHeight = getMeasuredHeight();
                measuredWidth = getMeasuredWidth();
                centerHeight = measuredHeight / 2;
                centerWidth = measuredWidth / 2;
                maxH = measuredHeight * 0.3F;
                minH = measuredHeight * 0.05F;
                time = "00:00";
                textPaint = new Paint();
                textPaint.setTextSize(30);//设置字体大小
                textPaint.setTextAlign(Paint.Align.CENTER);
                textPaint.setAntiAlias(true);
                textPaint.setColor(Color.BLUE);
                redPaint = new Paint();
                redPaint.setAntiAlias(true);
                redPaint.setStrokeWidth(4);
                redPaint.setColor(Color.parseColor("#B3B2B6"));
                maxCount = centerWidth / 25;
                count = maxCount;
                if (listener != null) {
                        listener.onSizeChange();
                }
                random = new Random();
        }

        @Override
        protected void onDraw(Canvas canvas) {
                super.onDraw(canvas);
                canvas.drawText(time, centerWidth, centerHeight + 8, textPaint);
                for (int i = 0; i <= count; i++) {
                        float v = random.nextFloat() * maxH + minH;
                        canvas.drawLine(centerWidth + i * 12 + 60, centerHeight - v, centerWidth + i * 12 + 60, centerHeight + v,
                                        redPaint);
                        canvas.drawLine(centerWidth - i * 12 - 60, centerHeight - v, centerWidth - i * 12 - 60, centerHeight + v,
                                        redPaint);
                }
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                super.onLayout(changed, left, top, right, bottom);
                Log.e(TAG, "onLayout");
        }

        public int getMaxCount() {
                return maxCount;
        }

        public void setOnSizeChangeListener(ISizeChangeListener listener) {
                this.listener = listener;
        }

        public interface ISizeChangeListener {

                void onSizeChange();
        }

        public void setCount(int count) {
                if (count <= 0) {
                        this.count = maxCount / 2;
                        return;
                }
                if (count > maxCount) {
                        this.count = maxCount;
                        return;
                }
                this.count = count;
        }


        public void startRecord() {
                Log.e(TAG, "startRecord");
                post(action);
                post(actionText);
                recorder();
        }

        public static final String RECORD_FILE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/record/";

        private void recorder() {
                mRecorder = new MediaRecorder();
                mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                File fileDIR = new File(RECORD_FILE_DIR);
                if (!fileDIR.exists()) {
                        fileDIR.mkdirs();
                }
                fileName = android.text.format.DateFormat.format("yyyy_MM_dd_HH_ss_mm", System.currentTimeMillis()).toString() + ".mp3";
                mRecorder.setOutputFile(RECORD_FILE_DIR + fileName);
                try {
                        mRecorder.prepare();
                        mRecorder.start();
                }
                catch (IOException e) {
                        Logger.e(TAG, e.getLocalizedMessage());
                        error();
                        return;
                }
        }

        private void error() {
                if (iErrorListener != null) {
                        iErrorListener.onError();
                }
                cancel();
        }

        public String ok() {
                destroy();
                return fileName;
        }

        private void stopRecorder() {
                try {
                        mRecorder.stop();
                }
                catch (IllegalStateException e) {
                        e.printStackTrace();
                }
                mRecorder.reset();   // You can reuse the object by going back to setAudioSource() step
                mRecorder.release(); // Now the object cannot be reused
                mRecorder = null;
        }

        private Runnable action = new Runnable() {
                @Override
                public void run() {
                        invalidate();
                        postDelayed(this, 200);
                }
        };

        private int recLen = 0;

        private int minute = 0;

        private Runnable actionText = new Runnable() {
                @Override
                public void run() {
                        recLen++;
                        if (recLen > 59) {
                                recLen = 0;
                                minute++;
                                if (minute < 10) {
                                        if (recLen < 10) {
                                                time = "0" + minute + ":0" + recLen;
                                        } else {
                                                time = "0" + minute + ":" + recLen;
                                        }
                                } else {
                                        if (recLen < 10) {
                                                time = "" + minute + ":0" + recLen;
                                        } else {
                                                time = "" + minute + ":" + recLen;
                                        }
                                }

                        } else {
                                if (minute < 10) {
                                        if (recLen < 10) {
                                                time = "0" + minute + ":0" + recLen;
                                        } else {
                                                time = "0" + minute + ":" + recLen;
                                        }
                                } else {
                                        if (recLen < 10) {
                                                time = "" + minute + ":0" + recLen;
                                        } else {
                                                time = "" + minute + ":" + recLen;
                                        }

                                }
                        }
                        invalidate();
                        postDelayed(this, 1000);
                }
        };

        private void destroy() {
                Log.e(TAG, "destroy");
                removeCallbacks(action);
                removeCallbacks(actionText);
                recLen = 0;
                minute = 0;
                time = "00:00";
                stopRecorder();
        }

        public int getTime(){
                return  minute*60+recLen;
        }
        public void cancel() {
                destroy();
                File file = new File(RECORD_FILE_DIR, fileName);
                if (file.exists()) {
                        file.delete();
                }
        }

        public void setErrorListener(IErrorListener iErrorListener) {
                this.iErrorListener = iErrorListener;
        }

        private IErrorListener iErrorListener;

        public interface IErrorListener {

                void onError();
        }
}
